<?php


namespace app\api\logic;

use app\common\library\exception\ParameterException;
use app\common\library\exception\OrderException;
use app\common\library\exception\UserException;
use think\Log;
use app\api\service\ApiPayment;

/**
 * 下单处理
 *
 *
 *
 */
class PrePay extends BaseApi
{
    /**
     *
     * 1.构建支付订单
     * 2.请求支付对象并返回商户
     * 3.用户扫码完成支付
     * 4.订单队列处理异步回调
     * 5.完成订单
     *
     * 构建支付订单
     *
     *
     * @param $orderData
     * @return mixed
     * @throws ParameterException
     */
    public function orderPay($orderData)
    {
        // 空值控制
        if (!is_null($orderData)) {

            //等所有基本数据检查完成后  对订单进行检查数据
            // $this->validateUnifiedOrder->goCheck();

            //TODO 订单持久化（估计用到队列）
            $order = $this->logicOrders->createPayOrder($orderData);

            //创建通过接口渠道订单
            //渠道和参数获取
            $appChannel = $this->logicPay->getAllowedAccount($order);
            if (isset($appChannel['errorCode'])) {
                Log::error($appChannel['msg']);
                throw new OrderException($appChannel);
            }

            //取出数据
            list($payment, $action, $config) = array_values($appChannel);

            //支付分发
            $result = ApiPayment::$payment($config)->$action($order);



            //取消队列 @2019/3/18
            // //写入订单超时队列
            // $this->logicQueue->pushJobDataToQueue('AutoOrderClose' , $order , 'AutoOrderClose');

            //提交支付 选择支付路由
            // $result = $this->logicDoPay->pay($order->trade_no);  //支付

            return $result;
        }
        throw new ParameterException([
            'msg'   => 'Create Order Error:[Order Fail].'
        ]);
    }

    /**
     * 查询订单
     *
     *
     * @param $queryData
     *
     * @return mixed
     * @throws ParameterException
     */
    public function orderQuery($queryData)
    {

        // 验证
        $this->validateQueryOrder->gocheck();

        try {
            $order = $this->logicOrders->getOrderInfo([
                'uid' => $queryData['app_id'],
                'out_trade_no' => $queryData['order_id']
            ], [
                'trade_no', 'out_trade_no', 'income', 'status'
            ]);


            return [
                "order_id" => $order["out_trade_no"],
                "pay_seq" => $order["trade_no"],
                "pay_amt" => $order["income"],
                "pay_result" => $order["status"]
            ];

        } catch (\Exception $e) {
            Log::error($e->getMessage());
            throw new ParameterException([
                'msg'   => 'Query Order Error:[Order Fail].'
            ]);
        }
    }
}
